import {login, logout, getInfo} from '@/api/user'
import {getToken, setToken, removeToken, getRefreshToken, setRefreshToken, removeRefreshToken} from '@/utils/auth'
import {resetRouter} from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    refreshToken: getRefreshToken(),
    username: '',
    nickname: '',
    avatar: '',
    roles: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  },
  SET_NICKNAME: (state, nickname) => {
    state.nickname = nickname
  },
  SET_REFRESHTOKEN: (state, refreshToken) => {
    state.refreshToken = refreshToken
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // 用户登录
  login({commit}, userInfo) {
    // 登录信息
    const {username, password} = userInfo
    return new Promise((resolve, reject) => {
      login({username: username.trim(), password: password}).then(response => {

        // 响应信息
        const {token, refreshToken, tokenHead} = response.data

        // token
        commit('SET_TOKEN', tokenHead + token)
        setToken(token)

        // refreshToken
        setRefreshToken(refreshToken)
        commit('SET_REFRESHTOKEN', refreshToken)

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getInfo({commit, state}) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const {data} = response
        // 如果没有数据
        if (!data) {
          return reject('验证失败,请重新登录')
        }
        // 获取信息
        const {username, nickName, avatar, roles} = data
        commit('SET_USERNAME', username)
        commit('SET_NICKNAME', nickName)
        commit('SET_AVATAR', avatar)
        commit('SET_ROLES', roles)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 退出登录
  logout({commit, state}) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        removeToken() // 移除token
        removeRefreshToken() // 移除 refresh_token
        resetRouter() // 重置路由
        commit('RESET_STATE') // 移除vuex中的数据
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 移除token
  resetToken({commit}) {
    return new Promise(resolve => {
      removeToken() // 移除token
      removeRefreshToken() // 移除 refresh_token
      commit('RESET_STATE') // 移除vuex中的数据
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

